import tensorflow as tf
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
from tensorflow import keras


def preprocess(x, y):
    """
    x is a simple image, not a batch
    """
    x = tf.cast(x, dtype=tf.float32) / 255.
    x = tf.reshape(x, [28 * 28])
    y = tf.cast(y, dtype=tf.int32)
    y = tf.one_hot(y, depth=10)
    return x, y


batchsz = 128
(x, y), (x_val, y_val) = datasets.mnist.load_data()
print('datasets:', x.shape, y.shape, x.min(), x.max())

db = tf.data.Dataset.from_tensor_slices((x, y))
db = db.map(preprocess).shuffle(60000).batch(batchsz)
ds_val = tf.data.Dataset.from_tensor_slices((x_val, y_val))
ds_val = ds_val.map(preprocess).batch(batchsz)

sample = next(iter(db))
print(sample[0].shape, sample[1].shape)


network = Sequential([
    layers.Dense(256, activation='relu'),
    layers.Dense(128, activation='relu'),
    layers.Dense(64, activation='relu'),
    layers.Dense(32, activation='relu'),
    layers.Dense(10)
])
network.build(input_shape=(None, 28 * 28))
network.summary()


# 创建网络层容器类
class MyDense(layers.Layer):

    # 初始化方法
    def __init__(self, inp_dim, outp_dim):
        # 调用父类的初始化函数
        super(MyDense, self).__init__()
        # 创建权值和偏置张量，并添加到类管理列表中
        self.kernel = self.add_weight('w', [inp_dim, outp_dim])
        self.bias = self.add_weight('b', [outp_dim])

    # 前向传播方法
    def call(self, inputs, training=None):
        # 前向计算 out = x*w+b
        out = inputs @ self.kernel + self.bias

        return out


# 模型
class MyModel(keras.Model):
# 自定义网络类，继承自Model基类
    def __init__(self):
        super(MyModel, self).__init__()

        # 使用自定义网络类，完成网络层的创建
        self.fc1 = MyDense(28 * 28, 256)
        self.fc2 = MyDense(256, 128)
        self.fc3 = MyDense(128, 64)
        self.fc4 = MyDense(64, 32)
        self.fc5 = MyDense(32, 10)

    # 前向传播方法
    def call(self, inputs, training=None):
        x = self.fc1(inputs)
        x = tf.nn.relu(x)
        x = self.fc2(x)
        x = tf.nn.relu(x)
        x = self.fc3(x)
        x = tf.nn.relu(x)
        x = self.fc4(x)
        x = tf.nn.relu(x)
        x = self.fc5(x)

        return x


network = MyModel()

# 模型装配
# 采用Adam优化器，学习率为0.1；采用交叉熵损失函数，包含Softmax
network.compile(optimizer=optimizers.Adam(lr=0.01),
                loss=tf.losses.CategoricalCrossentropy(from_logits=True),
                metrics=['accuracy']  # 测量指标为准确率
                )

# 模型训练
# 训练集为db，验证集为ds_val，训练5个epochs，每2个epch验证一次
network.fit(db, epochs=5, validation_data=ds_val, validation_freq=2)

print("*"*20)
# 模型测试
# 测试并打印出性能表现
network.evaluate(ds_val)

sample = next(iter(ds_val))
x = sample[0]
y = sample[1]  # one-hot
pred = network.predict(x)  # [b, 10]

# convert back to number
y = tf.argmax(y, axis=1) # 实际值
pred = tf.argmax(pred, axis=1) # 预测值

print("*"*20)
print(pred)
print("*"*20)
print(y)
